package com.zrh.jsd.service.studydemo.java8stream;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class AppleListStreamTest {
    public static void main(String[] args) {
        List<Apple> appleList = getAppleList();

        appleList.stream().collect(Collectors.groupingBy(a -> a.getColor(), // 基于颜色分组
                Collectors.averagingLong(a -> a.getWeight()))) // 统计平均重量  ,collect操作之后流变成map
                .forEach((k, v) -> System.out.println(k + ":" + v));

        appleList.stream().filter(a->"red".equals(a.getColor())) // 过滤颜色
                .collect(Collectors.toList())
                .forEach(a -> System.out.println(a.getId() + ":" + a.getOrigin() + ":" + a.getColor()));

        appleList.stream().filter(a -> a.weight > 200) // 过滤重量
                .collect(Collectors.toList())
                .forEach(a -> System.out.println(a.getId() + ":" + a.getOrigin() + ":" + a.getColor()));
        System.out.println("================================================");
        // 1、流的生成，与不可重复使用
        appleList.stream()
                .peek(a -> System.out.println(a.getId()))
                .peek(a -> System.out.println(a.getColor()))
                .peek(a-> System.out.println(a.getOrigin()))
                .toArray();
        System.out.println("================================================");
        // 采集：1、list 2、map 3、group by 4、数组 5、求出最大值 6、求任意值
        appleList.stream().collect(Collectors.toList());
        Map<String,Apple> map = appleList.stream().collect(Collectors.toMap(a->a.getColor(),a->a,(a1,a2)->a1));
        System.out.println(map);
    }

    public static List<Apple> getAppleList() {
        List<Apple> appleList = new ArrayList<>();
        appleList.add(new Apple(1, "red", 100, "北京"));
        appleList.add(new Apple(2, "green", 200, "北京"));
        appleList.add(new Apple(3, "green", 300, "衡水"));
        appleList.add(new Apple(4, "red", 200, "衡水"));
        appleList.add(new Apple(5, "green", 500, "河北"));
        appleList.add(new Apple(6, "red", 400, "河北"));
        return appleList;
    }
}
